import React, { Fragment, useContext, useEffect, useRef, useState } from 'react';
import Toast from './toast';
const ToastContext = React.createContext();

export function useToast(config) {
    const context = useContext(ToastContext);
    const show = (text, title) => {
        if (!context.showToast) {
            return;
        }

        if (title) {
            context.showToastWithTitle(text, title);
        } else {
            context.showToast(text);
        }
    };
    const showSuccess = (text) => {
        if (!context.showSuccess) {
            return;
        }

        context.showSuccess(text);

    };

    const hide = ()=>{
        context.hide()
    }
    return {
        showSuccess,
        show,
        hide
    };
}

export function DefaultToast(props) {
    const ref = useRef({});
    const forceUpdate = useState()[1];
    useEffect(
        () => {
            forceUpdate({});
        },
        [ref.current]
    );

    return (
        <Fragment>
            <ToastContext.Provider value={ref.current}>{props.children}</ToastContext.Provider>
            <Toast ref={ref} />
        </Fragment>
    );
}
